import axios from "axios";
import { Message } from "@arco-design/web-react";
import SessionStorageService from "@/SessionStorageService";

// 从SessionStorage中获取token
const token = SessionStorageService.getItem("token");
// 如果存在token，则将其添加到Authorization头中
const Authorization = token ? `Bearer ${token}` : "";
// 创建一个新的axios实例
const apiClient = axios.create({
  baseURL: "http://localhost:5005", // 替换为你的API基础路径
  headers: {
    "Content-Type": "application/json",
    Authorization: Authorization,
  },
  timeout: 10000, // 设置请求超时时间
});

// 定义GET请求
export const getRequest = (url, params = {}) => {
  return apiClient
    .get(url, { params })
    .then((response) => response.data)
    .catch((error) => {
      Message.error(error?.response?.data?.error);
      console.error("GET请求失败:", error);
      throw error;
    });
};

// 定义POST请求
export const postRequest = (url, data) => {
  return apiClient
    .post(url, data)
    .then((response) => response.data)
    .catch((error) => {
      Message.error(error?.response?.data?.error);
      console.error("POST请求失败:", error);
      throw error;
    });
};

// 定义PUT请求
export const putRequest = (url, data) => {
  return apiClient
    .put(url, data)
    .then((response) => response.data)
    .catch((error) => {
      Message.error(error?.response?.data?.error);
      console.error("PUT请求失败:", error);
      throw error;
    });
};
